/**
 *
 */
$(function(){
    $(document).keyup(function (e) {
        if(e.which==13){
            $('#selectBtnEnter').click();
        }
    })
});
var path = '../';
var pageListUrl = path + 'fConsume/list';
var pageListUrl1 = path + 'fConsume/flowWarningList';
var pageUrl = path + 'fConsume/';

//添加弹窗
var addPanel = null;
// ---------------交互代码begin-----------------
//本页面业务逻辑
var advPlay={
    checkLogic:function(dataObj){
        var result="";
        var isSubmit=true;
        //TODO 逻辑校验，去掉不必要的:
        //检查表单是否存在错误
        $.each(dataObj, function(key) {
            if(key.indexOf('Err')!=-1 && dataObj[key].length>0){
                return false;
            }
        });
        return isSubmit;
    }
};

//绑定列表List---begin----所有的操作都围绕列表展开，新增、更新其他比较独立
var dataList=new Vue({
    el:"#advPlayList",
    data:{
        pageInfo : {},
        //TODO 自定义条件查询---begin--------
        condition:{
            page:1,
            rows:customUtils.pageSize,
            id:"",
            // postionCode:"",
            // advCode:"",
            equipmentCode:"",
            param1:"2",
            param2:"",

            // playDate:"",

            startDate:"",
            overDate:"",
            // revisedDataDTO:{
            //     minAge:"",
            //     maxAge:""
            // },
            status:"",
        },
        msg:{
            sysErrorMsg:"",
            checkErrMsg:"",
            fieldErrMsg:"",
            success:""
        },
        province:"",
        city:"",
        area:"",

        provinces:[],
        citys:[],
        areas:[],

        //自定义条件查询---end--------
        selectIds:[],//多选
        showSuccess:false,//false不显示成功提示
        selectedIdx:-1,//保存操作行的索引
        isSearch:false,//init:页面初始化；search:点击查询；paging:点击翻页；changePageSize:改变页面显示条数
        selectedPageSize:customUtils.pageSize//修改页面数据显示条数
    },
    mounted: function () {
        //初始化页面数据
        this.getList('init');
        this.getAreaData();
    },
    // 在 `methods` 对象中定义方法,如果操作中函数的逻辑比较复杂，必须封装到dictType对象
    methods:{
        exportRecord:function () {
            var total = this.pageInfo.total;
            var msg = "您确定要导出" + total + " 条数据吗？请在导出操作之前先进行查询操作，无论是什么条件导出，服务器限制每次导出最多只支持5万条，请知悉，谢谢！";
            var self=this;
            var param1 = self.province?self.province.code:"";//省份
            var param2 = self.city?self.city.code:"";//城市
            var param3 = self.area?self.area.code:"";//区域
            var startDate = self.condition["startDate"];
            var overDate = self.condition["overDate"];
            var advCode = self.condition["advCode"];
            var equipmentCode = self.condition["equipmentCode"];
            layer.confirm(msg, function (index) {
                location.href=pageUrl+"exportRecord?param1="+param1+"&param2="+param2+"&param3="+param3+"&startDate="+startDate+"&overDate="+overDate
                    +"&advCode="+advCode+"&equipmentCode="+equipmentCode;
                layer.close(index);
                return true;
            });
            return false;
        },
        changeTime:function(elem){
            this.$data.condition[elem.split("-")[0]] = $("#"+elem).val();
        },
        getAreaData:function () {
            this.$http.get("../appInfo/queryAreaTree").then(function(response){
                console.log(response)
                dataList.$data.provinces = response.body;
                console.log(dataList.$data)
            },function (res) {

            });
        },
        setCitys:function () {
            dataList.$data.citys = dataList.$data.province.citys;
            dataList.$data.city = "";
            dataList.$data.area = "";
        },
        setAreas:function () {
            dataList.$data.areas = dataList.$data.city.areas;
            dataList.$data.area = "";
        },
        //搜索、分页列表
        getList:function(eventSrc){
            var self=this;
            //改变页面显示条数
            if(eventSrc=="changePageSize"){
                if(this.pageInfo.pageSize != this.selectedPageSize){
                    this.pageInfo.pageSize=this.selectedPageSize;
                    $('#pagination').jqPaginator('destroy');
                    eventSrc='init';//重新绘制控件
                }else{
                    return;
                }
            }
            //初始化时无当前页数，后台有默认第1页，每页10条
            if(this.pageInfo!=undefined && this.pageInfo.pageNum!=undefined){
                self.condition["page"]=this.pageInfo.pageNum;
                self.condition["rows"]=this.pageInfo.pageSize;
            }
            console.log(self)
            Vue.http.options.emulateJSON = false
            //发送请求,第一个参数http对象，第二个是url，第三个是参数，第四个是成功回调，第五个是请求失败回调
            customUtils.post(self,pageListUrl1,self.condition,function(response,isSuccess){
                if(isSuccess==false){
                    dataList.pageInfo.pages=0;
                    customUtils.noData('无数据',0);
                    return;
                }
                if(response.body.warningValue!=undefined){
                    self.condition.param2=response.body.warningValue;
                }
                dataList.pageInfo = response.body.pagination;
                customUtils.noData('无数据',dataList.pageInfo.pages);
                //页面初始化、搜索时，才需要执行分页控件
                if(eventSrc=='init' || eventSrc=='search'){
                    customUtils.paging('#pagination',dataList.pageInfo.pages,customUtils.showPage,function(num){
                        //当前页码pageNum与将要翻页的页码num不相等才执行，否则为同一页
                        if(dataList.pageInfo.pageNum!=num){
                            dataList.pageInfo.pageNum=num;
                            dataList.getList('paging');
                        }
                    });
                }
            },function(response){
                console.log(response);
                dataList.pageInfo.pages=0;
                customUtils.noData('无数据',0);
            });
        },
        //更新状态
        updateStatus:function(index){
            var record = this.pageInfo.list[index];
            var status = record.status==1?0:1;
            var param = {id:record.id,status:status};
            var self=this;
            customUtils.post(self,pageUrl + 'update',param,function(response,isSuccess){
                record.status=status;
                //根据需要刷新页面数据
                dataList.getList('init');
            },function(response){
                //console.log(response.body);
            });
        },
        //初始化更新，更新对话框
        updateInit:function(index){
            //先显示窗口，才有加载效果
            this.addOrUpdatePanel("update");
            var record = this.pageInfo.list[index];
            this.selectedIdx=index;
            var url = pageUrl + 'id/'+record.id;
            var self=this;
            customUtils.get(self.$http,url,function(response,isSuccess){
                if(isSuccess==false){
                    return;
                }
                //回显表单数据
                $.each(response.body, function(key) {
                    if(addOrUpdate[key]!==undefined && response.body[key]){
                        addOrUpdate[key] = response.body[key];
                    }
                });
            },function(response){
                console.log(response);
            });
        },
        //打开添加对话框
        addOrUpdatePanel:function(flag){
            //清除表单数据，否则会有前一条修改数据的内容
            $.each(addOrUpdate.$data, function(key) {
                addOrUpdate[key]="";
            });
            var tmpTitle =  flag=="add"?"添加":"修改";
            addPanel = layer.open({
                type : 1,
                title :tmpTitle+"广告播放报表",
                area : [ '570px', 'auto' ],
                shadeClose : false, // 点击遮罩关闭
                content : $('#addPanel')
            });
        },
        importPostion: function () {
            var obj3 = document.getElementById('file');
            obj3.outerHTML = obj3.outerHTML;
            importVue.fileErr = "";
            importPanel = layer.open({
                type: 1,
                title: "导入位置信息",
                area: ['600px', '70%'],
                shadeClose: false, // 点击遮罩关闭
                content: $('#importPanel')
            });
        },
        warningValueBtn:function () {
            var self=this;
            var warningValue = self.condition.param2;//流量预警值设定
            this.$http.get("../fConsume/setWarningValue?warningValue="+warningValue).then(function(response){
                if(response.body.status=="success") {
                    customUtils.tips(response.body.msg, 1, 1000);
                }else{
                    this.$data.msg.checkErrMsg=response.body.msg;
                    customUtils.showTips(this.$data.msg,null,3000);
                }
            },function (res) {
            });
        }
    }
});
//绑定列表List---end----

//新增或更新---------begin-------
var addOrUpdate = new Vue({
    el:"#addPanel",
    data:{
        postionCode:"",
        equipmentCode:"",
        advCode:"",
        sex:"",

        advPath:"",
        id:"",
        //以下是错误信息
        postionCodeErr:"",
        equipmentCodeErr:"",
        advCodeErr:"",
        sexErr:"",
        advPathErr:"",
        showSuccess:true,//显示成功提示
    },
    //当需要在数据变化时执行异步或开销较大的操作时，这个方式是最有用的
    watch:{
    },
    methods:{

        save:function(){
            //逻辑校验
            if(!advPlay.checkLogic(this.$data)){
                return;
            }
            //没有id的时候表示新增，否则为更新
            var actionUrl=this.id=="" ? 'save' :'update';
            var self=this;
            customUtils.post(self,pageUrl + actionUrl,self.$data,function(response,isSuccess){
                if(actionUrl=='update'){
                    var record = dataList.pageInfo.list[dataList.selectedIdx];
                    //更新成功，刷新列表中对应的数据
                    $.each(record, function(key) {
                        if(addOrUpdate[key]!=undefined){
                            record[key]=addOrUpdate[key];
                        }
                    });
                }else if(isSuccess){
                    dataList.getList('init');
                }
                if(isSuccess && addPanel)layer.close(addPanel);
            },function(res){
                //console.log(response.body);
            });
        },
        //清除表单数据
        reset:function(){
            $.each(addOrUpdate.$data, function(key) {
                addOrUpdate[key]="";
            });
        }
    }
});
//本页面业务逻辑
var postion = {
    checkLogic: function (dataObj) {
        var result = "";
        var isSubmit = true;
        //TODO 逻辑校验，去掉不必要的:
        //检查表单是否存在错误
        $.each(dataObj, function (key) {
            if (key.indexOf('Err') != -1 && dataObj[key].length > 0) {
                return false;
            }
        });
        return isSubmit;
    },
    checkFileType: function () {
        var fileName = $("#file")[0].files[0].name;
        var fileType = fileName.substr(fileName.lastIndexOf(".") + 1, fileName.length);
        if (fileType.toUpperCase() != 'XLSX' && fileType.toUpperCase() != 'XLS') {
            importVue.fileErr = "请选择*.xlsx或者*.xls格式的Excel文件";
            return false;
        }
        return true;
    }
};
//新增或更新---------end-------
var importVue = new Vue({
    el: "#importPanel",
    data: {
        fileErr: ""
    },
    methods: {
        importB: function () {
            var self = this;
            if (!postion.checkFileType()) {
                return;
            }
            console.log($("#importPanel"))
            console.log($("#importPanel").find("#file")[0].files)
            var formDate = new FormData($("#importPanel")[0]);
            //没选择文件时
            if ($("#importPanel").find("#file")[0].files.length <= 0) {
                $(".errMsg").html("请选择要上传的数据文件");
                return;
            }
            customUtils.post(self, pageUrl + "upload", formDate, function (response) {
                console.log(response);
                customUtils.showTips(response.body, null, 2000);
                var html = "";
                if (response.body.errList != 'undefined' && response.body.errList != '' && response.body.errList != null) {
                    response.body.errList.forEach(function (value, index) {
                        html = html + value + "<br>";
                    });
                    $(".errMsg").html(html);
                } else {
                    if (importPanel) layer.close(importPanel);
                    dataList.getList('init');
                }
            }, function (response) {
                customUtils.showRequestTips(response, 3000)
            })
            console.log(formDate);
        }
    }

});

var path = "../";

var lineList = [];
var date = [];
var echartList = [];
var flowUpload = echarts.init(document.getElementById('chartToUpload'));
var flowDownload = echarts.init(document.getElementById('chartToDownload'));
var flowTotal = echarts.init(document.getElementById('chartToTotal'));
function getFlowToday() {
    chartToFlowTodayLineFunction('1');
    chartToFlowTodayLineFunction('2');
    chartToFlowTodayLineFunction('3');
}
function getFlowWeekend() {
    chartToFlowBarFunction('1','2');
    chartToFlowBarFunction('2','2');
    chartToFlowBarFunction('3','2');
}
function getFlowMonth() {
    chartToFlowBarFunction('1','3');
    chartToFlowBarFunction('2','3');
    chartToFlowBarFunction('3','3');
}
function chartToFlowTodayLineFunction(type) {
    if(type=='1'){
        var chart = flowUpload;
    }
    if(type=='2'){
        var chart = flowDownload;
    }
    if(type=='3'){
        var chart = flowTotal;
    }
    $.ajax({
        type: "post",
        async: true,            //异步请求（同步请求将会锁住浏览器，用户其他操作必须等待请求完成才可以执行）
        url: path + "fConsume/chartToFlow",
        data: {param1:'1'},
        dataType: "json",        //返回数据形式为json
        success: function (result) {
            //请求成功时执行该函数内容，result即为服务器返回的json对象
            if (result.todayList.length != undefined) {
                todayList = [];
                yestodayList = [];
                date = [];
                flowName = '';
                totalTodayFlow= '';
                if(type=='1'){
                    flowName='上传';
                    totalTodayFlow = result.totalTodayFlow.todayUploadFlow;
                    for (var i = 0; i < result.todayList.length; i++) {
                        if (result.todayList[i].uploadFlow != undefined) {
                            todayList.push(result.todayList[i].uploadFlow);
                        }
                    }
                    for (var i = 0; i < result.yestodayList.length; i++) {
                        if (result.yestodayList[i].uploadFlow != undefined) {
                            yestodayList.push(result.yestodayList[i].uploadFlow);
                            date.push(result.yestodayList[i].dateName);
                        }
                    }
                }
                if(type=='2'){
                    flowName='下载';
                    totalTodayFlow = result.totalTodayFlow.todayDownloadFlow;
                    for (var i = 0; i < result.todayList.length; i++) {
                        if (result.todayList[i].downloadFlow != undefined) {
                            todayList.push(result.todayList[i].downloadFlow);
                        }
                    }
                    for (var i = 0; i < result.yestodayList.length; i++) {
                        if (result.yestodayList[i].downloadFlow != undefined) {
                            yestodayList.push(result.yestodayList[i].downloadFlow);
                            date.push(result.yestodayList[i].dateName);
                        }
                    }
                }
                if(type=='3'){
                    flowName='总';
                    totalTodayFlow = result.totalTodayFlow.todayTotalFlow;
                    for (var i = 0; i < result.todayList.length; i++) {
                        if (result.todayList[i].totalFlow != undefined) {
                            todayList.push(result.todayList[i].totalFlow);
                        }
                    }
                    for (var i = 0; i < result.yestodayList.length; i++) {
                        if (result.yestodayList[i].totalFlow != undefined) {
                            yestodayList.push(result.yestodayList[i].totalFlow);
                            date.push(result.yestodayList[i].dateName);
                        }
                    }
                }
                chart.clear();
                var option=setOptionParamTodayline(result);
                chart.setOption(option);
            } else {
                chart.clear();
                option.series[0].data = "暂无数据"
                chart.setOption(option);
            }
        },
        error: function (errorMsg) {
            //请求失败时执行该函数
            alert("图表请求数据失败!");
            chart.hideLoading();
        }
    });
};

function chartToFlowBarFunction(type,flowType) {
    if(type=='1'){
        var chart = flowUpload;
    }
    if(type=='2'){
        var chart = flowDownload;
    }
    if(type=='3'){
        var chart = flowTotal;
    }
    $.ajax({
        type: "post",
        async: true,            //异步请求（同步请求将会锁住浏览器，用户其他操作必须等待请求完成才可以执行）
        url: path + "fConsume/chartToFlow",    //请求发送到getTig处
        data: {param1:flowType},
        dataType: "json",        //返回数据形式为json
        success: function (result) {
            //请求成功时执行该函数内容，result即为服务器返回的json对象
            if (result.flowList.length != undefined) {
                echartList = [];
                date = [];
                flowName = '';
                avgTodayFlow= '';
                if(type=='1'){
                    flowName='上传';
                    avgTodayFlow = result.avgFlow.avgUploadFlow;
                    for (var i = 0; i < result.flowList.length; i++) {
                        if (result.flowList[i].uploadFlow != undefined) {
                            echartList.push(result.flowList[i].uploadFlow);
                            date.push(result.flowList[i].dateName);
                        }
                    }
                }
                if(type=='2'){
                    flowName='下载';
                    avgTodayFlow = result.avgFlow.avgDownloadFlow;
                    for (var i = 0; i < result.flowList.length; i++) {
                        if (result.flowList[i].downloadFlow != undefined) {
                            echartList.push(result.flowList[i].downloadFlow);
                            date.push(result.flowList[i].dateName);
                        }
                    }
                }
                if(type=='3'){
                    flowName='总';
                    avgTodayFlow = result.avgFlow.avgTotalFlow;
                    for (var i = 0; i < result.flowList.length; i++) {
                        if (result.flowList[i].totalFlow != undefined) {
                            echartList.push(result.flowList[i].totalFlow);
                            date.push(result.flowList[i].dateName);
                        }
                    }
                }
                chart.clear();
                var option=setOptionParamBar(result);
                chart.setOption(option);
            } else {
                chart.clear();
                option.series[0].data = "暂无数据"
                chart.setOption(option);
            }
        },
        error: function (errorMsg) {
            //请求失败时执行该函数
            alert("图表请求数据失败!");
            chart.hideLoading();
        }
    });
};

function setOptionParamTodayline(result) {
    if (result.yestodayList.length != undefined) {
        var colors = ['#5793f3', '#d14a61', '#675bba'];
        option = {
            color: colors,
            title: {
                text: '今日'+flowName+'流量使用情况',
                x: 'center'
            },
            tooltip: {
                trigger: 'none',
                axisPointer: {
                    type: 'cross'
                }
            },
            graphic: [
                {
                    type: 'group',
                    right: '200px',
                    top: 1,
                    children: [
                        {
                            type: 'text',
                            z: 100,
                            left: 'center',
                            top: 'middle',
                            style: {
                                fill: '#333',
                                text: [
                                    '今日'+flowName+'流量使用总量：'+totalTodayFlow,
                                ].join('\n'),
                                font: '14px Microsoft YaHei'
                            }
                        }
                    ]
                }
            ],
            legend: {
                data:['今日', '昨日'],
                x: 'left'
            },
            grid: {
                top: 70,
                bottom: 50
            },
            xAxis: [
                {
                    type: 'category',
                    axisTick: {
                        alignWithLabel: true
                    },
                    axisLine: {
                        onZero: false,
                        lineStyle: {
                            color: colors[1]
                        }
                    },
                    axisPointer: {
                        label: {
                            formatter: function (params) {
                                return '昨日'+flowName+'流量  ' + params.value
                                    + (params.seriesData.length ? '：' + params.seriesData[0].data : '');
                            }
                        }
                    },
                    data: date
                },
                {
                    type: 'category',
                    axisTick: {
                        alignWithLabel: true
                    },
                    axisLine: {
                        onZero: false,
                        lineStyle: {
                            color: colors[0]
                        }
                    },
                    axisPointer: {
                        label: {
                            formatter: function (params) {
                                return '今日'+flowName+'流量  ' + params.value
                                    + (params.seriesData.length ? '：' + params.seriesData[0].data : '');
                            }
                        }
                    },
                    data: date
                }
            ],
            yAxis: [
                {
                    type: 'value'
                }
            ],
            toolbox: {
                feature: {
                    saveAsImage: {}
                }
            },
            series: [
                {
                    name:'今日',
                    type:'line',
                    xAxisIndex: 1,
                    smooth: true,
                    data: todayList
                },
                {
                    name:'昨日',
                    type:'line',
                    smooth: true,
                    data: yestodayList
                }
            ]
        };
        return option;
    } else {

    }
};

/*
function setOptionParamTodayline(result) {
    if (result.yestodayList.length != undefined) {
        var option = {
            title: {
                text: '今日'+flowName+'流量使用情况'
            },
            tooltip: {
                trigger: 'axis'
            },
            legend: {
                data:['今日','昨日']
            },
            grid: {
                left: '3%',
                right: '4%',
                bottom: '3%',
                containLabel: true
            },
            toolbox: {
                feature: {
                    saveAsImage: {}
                }
            },
            xAxis: {
                type: 'category',
                boundaryGap: false,
                data: date
            },
            yAxis: {
                type: 'value'
            },
            graphic: [
                {
                    type: 'group',
                    right: '200px',
                    top: 1,
                    children: [
                        {
                            type: 'text',
                            z: 100,
                            left: 'center',
                            top: 'middle',
                            style: {
                                fill: '#333',
                                text: [
                                    '今日'+flowName+'流量使用总量：'+totalTodayFlow,
                                ].join('\n'),
                                font: '14px Microsoft YaHei'
                            }
                        }
                    ]
                }
            ],
            series: [
                {
                    name:'今日',
                    type:'line',
                    stack: '总量',
                    data:todayList
                },
                {
                    name:'昨日',
                    type:'line',
                    stack: '总量',
                    data:yestodayList
                }
            ]
        };
        return option;
    } else {

    }
};
*/

function setOptionParamBar(result) {
    if (result.flowList.length != undefined) {
        var option = {
            /*title: {
                left: '5%',
                textStyle: {
                    fontSize: 25,
                    color: '#333'          // 主标题文字颜色
                },
                text: ''
            }*/
            title: {
                text: result.echartName+flowName+'流量使用情况',
                x: 'center'
            },
            /*tooltip: {},
            legend: {
                data: [result.echartName]
            },*/
            xAxis: {
                data: date
            },
            dataZoom: [{
                type: 'slider',
                show: true,
                xAxisIndex: [0],
                left: '9%',
                bottom: -5,
                start: 0,
                end: 100 //初始化滚动条
            }],
            yAxis: [
                {
                    axisLabel: {
                        formatter: '{value}'
                    }
                }
            ],
            graphic: [
                {
                    type: 'group',
                    right: '200px',
                    top: 1,
                    children: [
                        {
                            type: 'text',
                            z: 100,
                            left: 'center',
                            top: 'middle',
                            style: {
                                fill: '#333',
                                text: [
                                    result.echartName+flowName+'平均使用流量：'+avgTodayFlow,
                                ].join('\n'),
                                font: '14px Microsoft YaHei'
                            }
                        }
                    ]
                }
            ],
            toolbox: {
                show: true,
                orient: 'horizontal',
                showTitle: true,
                feature: {
                    magicType: {
                        type: ['line']
                    },
                    saveAsImage: {
                        type: 'png',
                        show: true,
                        title: '保存为图片',
                    },
                    restore: {show: true}
                }
            },
            series: [
                {
                    name: result.echartName,
                    type: 'bar',
                    data: echartList,
                    barWidth: '50%',
                    itemStyle:{
                        normal:{
                            label:{
                                show:true,
                                position:'top',
                                textStyle:{
                                    color:'black',
                                    fontSize:16
                                }
                            }
                        }
                    }
                }
            ]
        };
        return option;
    } else {

    }
};

